<template>
    <div class="ledger-wrap">
        <div class="toolbar">
            <el-button type="primary" class="main-btn" @click="handleAdd">添加设备台账</el-button>
            <el-button @click="toggleSelectAll" :disabled="tableData.length === 0">
                {{ isAllSelected ? '全不选' : '全选' }}
            </el-button>
            <el-button v-if="multipleSelection.length > 0" type="danger" class="main-btn" :loading="batchDeleteLoading"
                :disabled="batchDeleteLoading" @click="handleBatchDelete">
                批量删除
            </el-button>
        </div>
        <el-form :inline="true" :model="from" class="demo-form-inline search-form">
            <el-form-item label="设备名称">
                <el-input v-model="from.deviceName" placeholder="请输入设备名称" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" class="main-btn" @click="GetEquipmentLedgerlist">搜索</el-button>
            </el-form-item>
        </el-form>
        <div style="overflow-x:auto;">
            <el-table :data="tableData" border style="width: 100%" empty-text="暂无数据"
                @selection-change="handleSelectionChange" ref="tableRef">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="设备编号" width="180" />
                <el-table-column prop="deviceName" label="设备名称" width="180" />
                <el-table-column prop="equipment" label="设备说明" min-width="180">
                    <template #default="{ row }">
                        <el-tooltip class="item" effect="dark" :content="row.equipment" placement="top">
                            <span class="ellipsis">{{ row.equipment }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="provider" label="供应商" width="180">
                    <template #default="{ row }">
                        <el-tooltip class="item" effect="dark" :content="row.provider" placement="top">
                            <span class="ellipsis">{{ row.provider }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="state" label="状态" width="120">
                    <template #default="{ row }">
                        <el-tag
                            :type="row.state === 0 ? 'success' : row.state === 1 ? 'info' : row.state === 2 ? 'danger' : row.state === 3 ? 'warning' : ''"
                            disable-transitions>
                            {{ row.state === 0 ? '正常' : row.state === 1 ? '禁用' : row.state === 2 ? '故障' : row.state ===
                                3 ?
                                '维修中' : '-' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createDateTime" label="创建时间" width="180" />
                <el-table-column label="操作" min-width="180">
                    <template #default="scope">
                        <div class="action-btns">
                            <el-button type="primary" size="small" class="main-btn" @click="onEdit(scope.row)">
                                <i class="el-icon-edit"></i> 编辑
                            </el-button>
                            <el-button type="danger" size="small" class="main-btn" @click="onDelete(scope.row.id)">
                                <i class="el-icon-delete"></i> 删除
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="Page.totalCount"
            :page-size="from.PageSize" :current-page="from.PageIndex" :page-sizes="[10, 20, 50, 100]"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"
            style="margin-top: 20px; text-align: right;" />
    </div>
    <!-- 添加设备台账对话框 -->
    <div>
        <el-dialog v-model="dialogVisible" title="添加设备台账" width="50%">
            <el-form ref="formRef" :model="result" :rules="rules" label-width="120px">
                <el-form-item label="设备名称" prop="deviceName">
                    <el-input v-model="result.deviceName" placeholder="请输入设备名称" />
                </el-form-item>
                <el-form-item label="设备说明" prop="equipment">
                    <el-input v-model="result.equipment" placeholder="请输入设备说明" />
                </el-form-item>
                <el-form-item label="供应商" prop="provider">
                    <el-input v-model="result.provider" placeholder="请输入供应商" />
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-radio-group v-model="result.state">
                        <el-radio :label="0">正常</el-radio>
                        <el-radio :label="1">禁用</el-radio>
                        <el-radio :label="2">故障</el-radio>
                        <el-radio :label="3">维修中</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="创建时间" prop="createDateTime">
                    <el-date-picker v-model="result.createDateTime" type="datetime" placeholder="请选择创建时间"
                        value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    <!-- 修改设备台账对话框 -->
    <div>
        <el-dialog v-model="dialogVisibleUpdate" title="修改设备台账" width="50%">
            <el-form ref="formRef" :model="resultUpdate" :rules="rules" label-width="120px">
                <el-form-item label="设备名称" prop="deviceName">
                    <el-input v-model="resultUpdate.deviceName" placeholder="请输入设备名称" />
                </el-form-item>
                <el-form-item label="设备说明" prop="equipment">
                    <el-input v-model="resultUpdate.equipment" placeholder="请输入设备说明" />
                </el-form-item>
                <el-form-item label="供应商" prop="provider">
                    <el-input v-model="resultUpdate.provider" placeholder="请输入供应商" />
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-radio-group v-model="resultUpdate.state">
                        <el-radio :label="0">正常</el-radio>
                        <el-radio :label="1">禁用</el-radio>
                        <el-radio :label="2">故障</el-radio>
                        <el-radio :label="3">维修中</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="创建时间" prop="createDateTime">
                    <el-date-picker v-model="resultUpdate.createDateTime" type="datetime" placeholder="请选择创建时间"
                        value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisibleUpdate = false">取消</el-button>
                    <el-button type="primary" @click="submitFormUpdate(formRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import axios from 'axios';
import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import http from '@/api/http.js'
import type data from '@/views/builder/builderData';
const router = useRouter()
import type { FormInstance, FormRules } from 'element-plus'
import { id } from 'element-plus/es/locales.mjs';
const formRef = ref<FormInstance>()
const route = useRoute()
const tableData = ref([]);
const dialogVisible = ref(false)
const dialogVisibleUpdate = ref(false)//修改对话框
const result = reactive({
    "deviceName": "",
    "equipment": "",
    "provider": "",
    "state": 0,
    "createDateTime": "",
})
//修改设备台账
const resultUpdate = reactive({
    id: '',
    "deviceName": "",
    "equipment": "",
    "provider": "",
    "state": '',
    "createDateTime": "",
})

// 表单验证规则
const rules = reactive<FormRules>({
    deviceName: [
        { required: true, message: '请输入设备名称', trigger: 'blur' }
    ],
    equipment: [
        { required: true, message: '请输入设备说明', trigger: 'blur' }
    ],
    provider: [
        { required: true, message: '请输入供应商', trigger: 'blur' }
    ],
    state: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
    createDateTime: [
        { required: true, message: '请输入创建时间', trigger: 'blur' }
    ]
})

//提交设备台账
const handleAdd = () => {
    dialogVisible.value = true
    // 重置表单
    if (formRef.value) {
        formRef.value.resetFields()
    }
}
// 提交表设备台账
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post('/api/EquipmentLedgerController/AddEquipmentLedgerAsync', result).then(res => {
                ElMessage.success('提交成功')
                GetEquipmentLedgerlist();
                dialogVisible.value = false
            }).catch(err => {
                ElMessage.error('提交失败')
            })
        } else {
            ElMessage.error('请检查输入内容')
        }
    })
}
const from = reactive({
    deviceName: '',
    PageIndex: 1,
    PageSize: 10,

})
const Page = reactive({
    totalCount: 0,
    totalPage: 0,
})
const GetEquipmentLedgerlist = () => {
    http.get(`api/EquipmentLedgerController/GetEquipmentLedger?PageIndex=${from.PageIndex}&PageSize=${from.PageSize}&DeviceName=${from.deviceName}`, {
        params: {
            deviceName: from.deviceName,
            PageIndex: from.PageIndex,
            PageSize: from.PageSize,
        }
    }).then(res => {
        tableData.value = res.items;
        Page.totalCount = res.totalCount;
        Page.totalPage = res.totalPage;
        nextTick(() => {
            tableRef.value?.clearSelection();
        });
    })
}
onMounted(() => {
    GetEquipmentLedgerlist();
})
function onEdit(row: any) {
    // 编辑逻辑
    dialogVisibleUpdate.value = true
    resultUpdate.id = row.id
    resultUpdate.deviceName = row.deviceName
    resultUpdate.equipment = row.equipment
    resultUpdate.provider = row.provider
    resultUpdate.state = row.state
    resultUpdate.createDateTime = row.createDateTime
}
//修改表设备台账
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post('/api/EquipmentLedgerController/UpdateEquipmentLedgerAsync', resultUpdate).then(res => {
                ElMessage.success('修改成功')
                GetEquipmentLedgerlist();
                dialogVisibleUpdate.value = false
            }).catch(err => {
                ElMessage.error('修改失败')
            })
        } else {
            ElMessage.error('请检查输入内容')
        }
    })
}
function onDelete(id: any) {
    // 删除逻辑
    ElMessageBox.confirm('确定删除该设备吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        http.get(`/api/EquipmentLedgerController/DelEquipmentLedgerAsync?id=${id}`, {
            data: {
                id: id
            }
        }).then(res => {
            console.log(res)
            ElMessage.success('删除成功')
            GetEquipmentLedgerlist()
        })
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

const tableRef = ref();
const multipleSelection = ref<any[]>([]);

function handleSelectionChange(val: any[]) {
    multipleSelection.value = val;
}
const batchDeleteLoading = ref(false);

function handleBatchDelete() {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请先选择要删除的设备');
        return;
    }
    ElMessageBox.confirm(
        `确定要删除选中的${multipleSelection.value.length}个设备吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        batchDeleteLoading.value = true;
        const ids = multipleSelection.value.map(item => item.id);
        http.post(`/api/EquipmentLedgerController/BatchDeleteEquipmentLedgerAsync?ids=${ids}`)
            .then(() => {
                ElMessage.success('批量删除成功');
                GetEquipmentLedgerlist();
                tableRef.value.clearSelection();
            })
            .catch(() => {
                ElMessage.error('批量删除失败');
            })
            .finally(() => {
                batchDeleteLoading.value = false;
            });
    });
}
function handleSizeChange(val: number) {
    from.PageSize = val;
    from.PageIndex = 1;
    GetEquipmentLedgerlist();
    nextTick(() => {
        tableRef.value?.clearSelection();
    });
}
function handleCurrentChange(val: number) {
    from.PageIndex = val;
    GetEquipmentLedgerlist();
    nextTick(() => {
        tableRef.value?.clearSelection();
    });
}
const isAllSelected = computed(() => {
    return tableData.value.length > 0 && multipleSelection.value.length === tableData.value.length;
});

function toggleSelectAll() {
    if (isAllSelected.value) {
        tableRef.value.clearSelection();
    } else {
        tableData.value.forEach(row => {
            tableRef.value.toggleRowSelection(row, true);
        });
    }
}
</script>
<style scoped>
.ledger-wrap {
    padding: 24px 32px;
    background: #f5f7fa;
    min-height: 100vh;
    max-width: 1600px;
    margin: 0 auto;
    box-sizing: border-box;
}

.toolbar {
    display: flex;
    gap: 16px;
    margin-bottom: 18px;
    justify-content: flex-start;
    flex-wrap: wrap;
}

.main-btn {
    border-radius: 8px !important;
    font-weight: 500;
    letter-spacing: 1px;
    transition: box-shadow 0.2s;
    margin-right: 12px;
    margin-bottom: 8px;
    display: inline-flex;
    align-items: center;
    font-size: 15px;
}

.main-btn:last-child {
    margin-right: 0;
}

.main-btn:hover {
    box-shadow: 0 2px 8px 0 rgba(64, 158, 255, 0.15);
}

.search-form {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 18px;
    flex-wrap: wrap;
}

.action-btns {
    display: flex;
    justify-content: center;
    gap: 8px;
}

.action-btns .el-button {
    border-radius: 16px;
    padding: 4px 14px;
    font-size: 14px;
    display: inline-flex;
    align-items: center;
}

.action-btns .el-button i {
    margin-right: 4px;
    font-size: 16px;
}

@media (max-width: 900px) {

    .toolbar,
    .search-form {
        flex-direction: column;
        align-items: stretch;
        gap: 8px;
    }

    .main-btn {
        width: 100%;
        margin-right: 0;
    }
}

.ellipsis {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
}
</style>